﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Mono.Cecil;
using System.IO;
using LiveSequence.Common.Engine;

namespace LiveSequence.Suite.Dialogs
{
  public partial class DlgAssemblyParserOptions : Form
  {
    private CecilAssemblyParserOptions _assemblyParserOptions;
    public DlgAssemblyParserOptions(string strFullPath)
    {
      InitializeComponent();
      InitializeComponentEx();

      _assemblyParserOptions = new CecilAssemblyParserOptions();
      GetAssemblyReferencesSet(strFullPath);

      
      List<CecilAssemblyOptions> lstSorted = new List<CecilAssemblyOptions>();
      foreach (KeyValuePair<string, CecilAssemblyOptions> keyPair in _assemblyParserOptions.AssemblyOptions.ToList())
      {
        lstSorted.Add(keyPair.Value);
      }

      _dgvAssemblyOptions.DataSource = lstSorted;
    }

    private void InitializeComponentEx()
    {
      _dgvAssemblyOptions.AutoGenerateColumns = false;
      DataGridViewTextBoxColumn txtCol;
      DataGridViewCheckBoxColumn chkCol; 

      txtCol = new DataGridViewTextBoxColumn();
      txtCol.DataPropertyName = "AssemblyName";
      txtCol.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
      txtCol.HeaderText = "Assembly Name";
      _dgvAssemblyOptions.Columns.Add(txtCol);

      chkCol = new DataGridViewCheckBoxColumn();
      chkCol.DataPropertyName = "Ignored";
      chkCol.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
      chkCol.MinimumWidth = 50;
      chkCol.Width = 50;
      chkCol.HeaderText = "Ignored";
      _dgvAssemblyOptions.Columns.Add(chkCol);
      
      txtCol = new DataGridViewTextBoxColumn();
      txtCol.DataPropertyName = "FullPath";
      txtCol.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
      txtCol.HeaderText = "Full Path";
      _dgvAssemblyOptions.Columns.Add(txtCol);


    }

    public CecilAssemblyParserOptions CecilAssemblyParserOptions
    {
      get { return _assemblyParserOptions; }
    }

    public void GetAssemblyReferencesSet(string strFullPath)
    {
      AssemblyDefinition assemblyDef = AssemblyFactory.GetAssemblyManifest(strFullPath);
      foreach (AssemblyNameReference asmRef in assemblyDef.MainModule.AssemblyReferences)
      {
        // see if there is a file with asmRef.dll name
        // construct path
        // get the directory from the assemblyfilename
        string referencedAssemblyPath = Path.Combine(Path.GetDirectoryName(strFullPath),
                                                     asmRef.Name + ".dll");

        _assemblyParserOptions.AddAssembly(asmRef.Name, referencedAssemblyPath);

        if (File.Exists(referencedAssemblyPath))
        {
          GetAssemblyReferencesSet(referencedAssemblyPath);
        }
      }
    }
  }
}
